package me.yricky.hid.desktop.mainnav

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import me.yricky.hid.desktop.AppState
import me.yricky.hid.desktop.Theme
import me.yricky.usbhid.HidDevice

class MainNavDeviceList(private val appState: AppState): MainNav() {

    var deviceList by mutableStateOf(emptyList<HidDevice>())
        private set

    fun refreshList(){
        appState.ioScope.launch {
            deviceList.forEach {
                if(it.isOpened()){
                    it.close()
                }
            }
            deviceList = appState.hid.getDevices()
        }
    }
    @Composable
    override fun Content(modifier: Modifier) {
        Box(modifier = Modifier.fillMaxSize()) {
            LazyColumn {
                items(deviceList.sortedBy { it.path }, key = { it.path }){
                    Surface(
                        modifier = Modifier.fillMaxWidth().padding(8.dp,4.dp),
                        shape = RoundedCornerShape(16.dp),
                    ) {
                        Column(
                            Modifier.clickable {
                                appState.mainNavDebugTabs.openTab(it)
                                appState.mainNav = appState.mainNavDebugTabs
                            }.padding(12.dp)
                        ) {
                            Text("${it.productName} (${it.manufacturerName})")
                            Text(String.format("%04x:%04x",it.vendorId,it.productId))
                            Text("path:${it.path}")
                            Text("serialNum:${it.serialNumber};releaseNum:${it.releaseNumber};interfaceNum:${it.interfaceNumber};busType:${it.busType}")
                        }
                    }
                }
            }
            FloatingActionButton(
                onClick = { refreshList() },
                modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp)
            ){
                Icon(Theme.Icons.refresh(),"refresh")
            }
        }

    }
}